package model;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;



/**
 * Compiles a template body with the given set of tokens
 * 
 * @author Musab Masood Mirza
 *
 * @version $Revision: 1.0 $
 */
public class TemplateCompiler {

	/**
	 * Token start pattern
	 */
	private static final String tokenStart = "\\$\\{";
	
	/**
	 * Token end pattern
	 */
	private static final String tokenEnd = "\\}";
	
	/**
	 * List of valid tokens
	 */
	HashMap<String, String> tokens;
	
	/**
	 * The text which needs to be compiled
	 */
	String body;
	
	
	/**
	 * Constructor
	 */
	public TemplateCompiler(){
		
		body = "";
		tokens = new HashMap<String, String>();
	}
	
	/**
	 * Clears the body and tokens
	 */
	public void clear(){
		body = "";
		tokens.clear();
	}

	/**
	 * Sets the tokens hashmap
	 * 
	 * @param tokens The tokens hashmap
	 */
	public void setTokens(HashMap<String, String> tokens){
		this.tokens = tokens;
	}
	
	/**
	 * Adds a new token or replaces an existing one
	 * 
	 * @param key Token key
	 * @param value Token value
	 */
	public void addOrReplaceToken(String key, String value){
		tokens.put(key, value);
	}
	
	/**
	 * Sets the body string
	 * 
	 * @param body The body string
	 */
	public void setBody(String body){
		this.body = body;
	}
	
	/**
	 * Returns the compiled version of the body
	 * 
	
	 * @return Compiled version of the body */
	public String compile(){
		
		// get a copy of the body string
		String compiled = body;
		
		// Replace all token occurances
		for (Map.Entry<String, String> entry : tokens.entrySet()){
			compiled = compiled.replaceAll(tokenStart + entry.getKey() + tokenEnd, entry.getValue());
		}
		
		// Replacing date and time
		Date date = new Date();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat timeFormat = new SimpleDateFormat("HH:mm a");
		compiled = compiled.replaceAll(tokenStart + "date" + tokenEnd, dateFormat.format(date));
		compiled = compiled.replaceAll(tokenStart + "time" + tokenEnd, timeFormat.format(date));
		
		return compiled;
	}
	
	
}
